package com.region.integral.common_user.obtain.dao.impl;

import java.util.List;

import org.springframework.stereotype.Component;

import com.region.integral.common_user.obtain.dao.IIntegralSendWeiBo;
import com.region.integral.common_user.obtain.vo.IntegralData;
import com.region.integral.common_user.pojo.CUIEntity;
import com.region.integral.common_user.xml.Regulation;
import com.region.integral.common_user.xml.dto.GroupPeopleRise;
import com.region.integral.common_user.xml.dto.SendWeiBo;
import com.region.integral.exception.IntegralException;
import com.region.integral.hibernate.BaseHibernate;
import com.region.integral.util.XMLRegulationUtil;
@Component("iSendWeiBo")
public class IntegralSendWeiBoImpl extends BaseHibernate implements IIntegralSendWeiBo {

	@Override
	public void sendWeiBo(int userid,String medal,IntegralData integralData)throws IntegralException {
		CUIEntity cuiEntity = getCUIEntity(userid);
		if (cuiEntity != null) {
			int sendWeiBoNum = cuiEntity.getSendWeiBoNum();
			
			Regulation regulation = XMLRegulationUtil.unmarshaller();
			List<SendWeiBo> sendWeiBos = regulation.getSendweibo();
			for (SendWeiBo sendWeiBo : sendWeiBos) {
				if (sendWeiBoNum == 0 && "frist".equals(sendWeiBo.getFrist())) {
					int currIntegral = cuiEntity.getCurrIntegral();
					int maxIntegral = cuiEntity.getMaxIntegral();
					int totalIntegral = currIntegral+ sendWeiBo.getIntegral();
					cuiEntity.setCurrIntegral(totalIntegral);
					if (maxIntegral < totalIntegral) {
						cuiEntity.setMaxIntegral(totalIntegral);
					}
					
					integralData.setSuccee(true);
					integralData.setObtainIntegral(sendWeiBo.getIntegral());
					hibernateTemplate.update(cuiEntity);
				}
				if(sendWeiBoNum!=0 && sendWeiBo.getRate()!=0&& sendWeiBoNum % sendWeiBo.getRate() == 0){
					int currIntegral = cuiEntity.getCurrIntegral();
					int maxIntegral = cuiEntity.getMaxIntegral();
					int totalIntegral = currIntegral+ sendWeiBo.getIntegral();
					cuiEntity.setCurrIntegral(totalIntegral);
					if (maxIntegral < totalIntegral) {
						cuiEntity.setMaxIntegral(totalIntegral);
					}
					integralData.setSuccee(true);
					integralData.setObtainIntegral(sendWeiBo.getIntegral());
					hibernateTemplate.update(cuiEntity);
				}
				if(sendWeiBo.getGetMedal()!=null && !"".equals(sendWeiBo.getGetMedal())&&sendWeiBo.getGetMedal().equals(medal)){
					int currIntegral = cuiEntity.getCurrIntegral();
					int maxIntegral = cuiEntity.getMaxIntegral();
					int totalIntegral = currIntegral+ sendWeiBo.getIntegral();
					if (maxIntegral < totalIntegral) {
						cuiEntity.setMaxIntegral(totalIntegral);
					}
					cuiEntity.setCurrIntegral(totalIntegral);
					hibernateTemplate.update(cuiEntity);
				}
				
			}
			cuiEntity.setSendWeiBoNum(sendWeiBoNum + 1);
			hibernateTemplate.update(cuiEntity);
		}
	}

}
